package com.sx.medicinecard.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayUserAgreementPageSignRequest;
import com.alipay.api.request.AlipayUserAgreementUnsignRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayUserAgreementPageSignResponse;
import com.alipay.api.response.AlipayUserAgreementUnsignResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.protobuf.ServiceException;
import com.sx.medicinecard.common.ResponseResult;
import com.sx.medicinecard.entity.SxAliAccountInfo;
import com.sx.medicinecard.entity.SxConfigInfo;
import com.sx.medicinecard.entity.SxOrderInfoBrush;
import com.sx.medicinecard.entity.SxSignContractBrush;
import com.sx.medicinecard.entity.dto.SxSignContractBrushDto;
import com.sx.medicinecard.mapper.SxAliAccountInfoMapper;
import com.sx.medicinecard.mapper.SxConfigInfoMapper;
import com.sx.medicinecard.mapper.SxOrderInfoBrushMapper;
import com.sx.medicinecard.mapper.SxSignContractBrushMapper;
import com.sx.medicinecard.service.SxSignContractBrushService;
import com.sx.medicinecard.utils.SnowflakeIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 签约表(SxSignContractBrush)表服务实现类
 *
 * @author makejava
 * @since 2024-07-17 18:31:30
 */
@Slf4j
@Service("sxSignContractBrushService")
public class SxSignContractBrushServiceImpl extends ServiceImpl<SxSignContractBrushMapper, SxSignContractBrush> implements SxSignContractBrushService {

    @Resource
    private SxSignContractBrushMapper sxSignContractBrushMapper;

    @Resource
    private SxAliAccountInfoMapper sxAliAccountInfoMapper;

    @Resource
    private SxOrderInfoBrushMapper sxOrderInfoBrushMapper;

    @Resource
    private SxConfigInfoMapper sxConfigInfoMapper;


    @Value("${ali.notifyUrl.signAndPayBrushCallBack}")
    private String signAndPayBrushCallBackUrl;

    @Value("${ali.notifyUrl.signAndPayBrushCallBackHy}")
    private String signAndPayBrushCallBackHyUrl;

    @Value("${ali.notifyUrl.signPayBrushCallBack}")
    private String signPayCallBackBrushUrl;
    @Override
    public ResponseResult signAndPay(SxSignContractBrushDto sxSignContractBrushDto, HttpServletRequest request) throws ServiceException, AlipayApiException, UnsupportedEncodingException {
        log.info("生成签约并支付链接(刷单)开始");

        // 获取配置的刷单限制天数
        SxConfigInfo sxConfigInfo = sxConfigInfoMapper.selectOne(null);
        Integer brushLimitDays = sxConfigInfo.getBrushLimitDays();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算限制天数前的日期
        LocalDate limitDate = currentDate.minusDays(brushLimitDays);

        // 检查在限制天数内是否存在订单记录
        boolean phoneNoExists = sxOrderInfoBrushMapper.exists(
                new QueryWrapper<SxOrderInfoBrush>()
                        .eq("phone_no", sxSignContractBrushDto.getPhoneNo())
                        .ge("create_time", limitDate)
        );

        if (phoneNoExists) {
            return ResponseResult.error("该手机号在限制天数内已下单，请勿重复下单");
        }

        SxAliAccountInfo sxAliAccountInfo = null;

        //从配置表获取支付宝账号
        if(StringUtils.isNotBlank(sxSignContractBrushDto.getAliAccountId())){
            sxAliAccountInfo = sxAliAccountInfoMapper.selectOne(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContractBrushDto.getAliAccountId()));
        }else {
            List<SxAliAccountInfo> sxAliAccountInfoList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("account_type", "2"));
            if(sxAliAccountInfoList.isEmpty()){
                throw new ServiceException("没有可用的支付宝账户，请联系管理员！");
            }
            //打乱支付宝账户列表取出第一个
            Collections.shuffle(sxAliAccountInfoList);
            sxAliAccountInfo = sxAliAccountInfoList.get(0);
        }

        if(sxAliAccountInfo==null){
            throw new ServiceException("没有可用的支付宝账户，请联系管理员！");
        }

        String signId = String.valueOf(SnowflakeIdUtils.generateId());

        //获取当前时间
        Date nowDate = new Date();

        //保存签约信息
        SxSignContractBrush sxSignContractBrush = new SxSignContractBrush();
        sxSignContractBrush.setSignId(signId);
        sxSignContractBrush.setPhoneNo(sxSignContractBrushDto.getPhoneNo());
        sxSignContractBrush.setChannelCode(sxSignContractBrushDto.getChannelCode());
        sxSignContractBrush.setPayType("0");
        sxSignContractBrush.setDeductType(sxAliAccountInfo.getDeductCycleType());//从支付宝账户获取扣款类型
        sxSignContractBrush.setDeductCycle(sxAliAccountInfo.getBrushCycle());//从支付宝账户获取周期
        sxSignContractBrush.setIsSignType("2");
        sxSignContractBrush.setAliAccountId(sxAliAccountInfo.getAliAccountId());//从支付宝账户获取id
        sxSignContractBrush.setCreateTime(nowDate);

        String signUrl = "";
        //生成链接
        if ("1".equals(sxAliAccountInfo.getAccountType())) {
            //单签约
            signUrl = signAliPay(sxSignContractBrush, sxAliAccountInfo,signPayCallBackBrushUrl);
        }else if ("2".equals(sxAliAccountInfo.getAccountType())) {
            //签约并支付
            signUrl = signAndAlipay(sxSignContractBrush, sxAliAccountInfo, signAndPayBrushCallBackUrl);
        }

        sxSignContractBrush.setSignUrl(signUrl);
        sxSignContractBrushMapper.insert(sxSignContractBrush);

        //获取支付宝跳转链接
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("url", signUrl);
        mapResult.put("signId", signId);

        return ResponseResult.success(mapResult);
    }

    /**
     * 签约并支付
     *
     * @param sxSignContractBrush
     * @param sxAliAccountInfo
     * @return
     */
    public String signAndAlipay(SxSignContractBrush sxSignContractBrush, SxAliAccountInfo sxAliAccountInfo,String callBackUrl){
        try{
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig(sxAliAccountInfo));
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            String yuankeOrderNo = "sd" + String.valueOf(SnowflakeIdUtils.generateId());
            model.setOutTradeNo(yuankeOrderNo);
            AgreementSignParams agreementSignParams = new AgreementSignParams();
            agreementSignParams.setExternalAgreementNo(sxSignContractBrush.getSignId());
            agreementSignParams.setPersonalProductCode(sxAliAccountInfo.getPersonalProductCode());
            agreementSignParams.setSignScene("INDUSTRY|DEFAULT_SCENE");

    //        String body = "首期0.01元，续期每月自动从您的支付宝账户扣款0.01元进行续费，可随时取消，取消后不再自动续费";
    //        String body = "首期"+sxAliAccountInfo.getBrushAmount()+"元，续期每月自动从您的支付宝账户扣款"+sxAliAccountInfo.getBrushAmount()+"元进行续费，可随时取消，取消后不再自动续费";
            model.setTotalAmount(String.valueOf(sxAliAccountInfo.getBrushAmount()));

            if(StringUtils.isNotBlank(sxAliAccountInfo.getBrushBody())) {
                SignMerchantParams subMerchant = new SignMerchantParams();
                subMerchant.setSubMerchantName(sxAliAccountInfo.getBrushSubject());
                subMerchant.setSubMerchantServiceName(sxAliAccountInfo.getBrushSubject());
                subMerchant.setSubMerchantServiceDescription(sxAliAccountInfo.getBrushBody());
                agreementSignParams.setSubMerchant(subMerchant);
            }

            model.setAgreementSignParams(agreementSignParams);
            model.setProductCode("GENERAL_WITHHOLDING");
            model.setIntegrationType("ALIAPP");

            model.setBody("源客项目");       //订单描述
            model.setSubject(sxAliAccountInfo.getBrushSubject());//商品描述

            JSONObject passbackParams = new JSONObject();
            passbackParams.put("signId", sxSignContractBrush.getSignId());
            passbackParams.put("totalAmount", model.getTotalAmount());
            passbackParams.put("signType","1");//刷单
            model.setPassbackParams(passbackParams.toString());
            //model.setPassbackParams("888");      //公用回传参数，如果请求时传递了该参数，则返回给商户时会回传该参数。
            request.setNotifyUrl(callBackUrl);
            request.setBizModel(model);

            request.setReturnUrl(sxAliAccountInfo.getBrushReturnUrl());
            request.putOtherTextParam("app_auth_token", sxAliAccountInfo.getAppAuthToken());  //从支付宝账户获取
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");

            String url = "https://render.alipay.com/p/c/mdeduct-landing?scheme=" + URLEncoder.encode("alipays://platformapi/startapp?appId=20000067&url=" + URLEncoder.encode(response.getBody(), "UTF-8"), "UTF-8");
            return url;
        }catch (AlipayApiException | UnsupportedEncodingException e){
            log.error("调用阿里生成签约并支付链接失败，返回参数：{}",e.getMessage());
        }
        return "";
    }

    //签约和支付
    public String signAliPay(SxSignContractBrush sxSignContractBrush, SxAliAccountInfo sxAliAccountInfo,String signCallBackUrl) throws AlipayApiException, UnsupportedEncodingException {

        String privateKey = sxAliAccountInfo.getPrivateKey();
        String alipayPublicKey = sxAliAccountInfo.getAlipayPublicKey();
        String appId = sxAliAccountInfo.getAppId();
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "GBK", alipayPublicKey, "RSA2");

        // 构造请求参数以调用接口
        AlipayUserAgreementPageSignRequest request = new AlipayUserAgreementPageSignRequest();
        AlipayUserAgreementPageSignModel model = new AlipayUserAgreementPageSignModel();

        // 设置请按当前接入的方式进行填充
        AccessParams accessParams = new AccessParams();
        accessParams.setChannel("ALIPAYAPP");
        model.setAccessParams(accessParams);

        // 设置周期管控规则参数period_rule_params
        PeriodRuleParams periodRuleParams = new PeriodRuleParams();
        periodRuleParams.setPeriod(Long.valueOf(sxAliAccountInfo.getBrushCycle())); //扣款周期30天 存数据库     //从支付宝账户获取
//      periodRuleParams.setTotalAmount("600");
        periodRuleParams.setExecuteTime(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));//当天日期
        periodRuleParams.setSingleAmount(sxAliAccountInfo.getBrushAmount().toString());  //签约金额
        periodRuleParams.setTotalPayments(12L);
        periodRuleParams.setPeriodType(sxAliAccountInfo.getDeductCycleType());  //扣款周期类型     //从支付宝账户获取
        model.setPeriodRuleParams(periodRuleParams);

        // 设置商户签约号
        model.setExternalAgreementNo(sxSignContractBrush.getSignId());  //商品签约号

        // 设置销售产品码
        model.setProductCode(sxAliAccountInfo.getProductCode());
        // 设置个人签约产品码
        //model.setPersonalProductCode("CYCLE_PAY_AUTH_P");
        model.setPersonalProductCode(sxAliAccountInfo.getPersonalProductCode());

        model.setSignScene("INDUSTRY|DEFAULT_SCENE");

        // 设置签约有效时间限制
        request.setNotifyUrl(signCallBackUrl);//设置异步通知地址   //改为配置文件

        request.setReturnUrl(sxAliAccountInfo.getReturnUrl());
        request.putOtherTextParam("app_auth_token", sxAliAccountInfo.getAppAuthToken());  //从支付宝账户获取
        request.setBizModel(model);
        // 如果需要返回GET请求，请使用
        AlipayUserAgreementPageSignResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        return "https://render.alipay.com/p/s/i/?scheme=" + URLEncoder.encode("alipays://platformapi/startapp?appId=20000067&url=" + URLEncoder.encode(response.getBody(), "UTF-8"), "UTF-8");
    }

    /**
     * 保存支付订单（刷单）
     *
     * @param sxSignContractBrush
     */
    public SxOrderInfoBrush createOrderBrush(SxSignContractBrush sxSignContractBrush,String yuankeOrderNo,String receiveId,JSONObject payData) {
        log.info("进入创建(刷单)订单");
        SxOrderInfoBrush sxOrderInfoBrush = new SxOrderInfoBrush();
        sxOrderInfoBrush.setOrderId(String.valueOf(SnowflakeIdUtils.generateId()));
        sxOrderInfoBrush.setPhoneNo(sxSignContractBrush.getPhoneNo());
        Long orderNum = sxOrderInfoBrushMapper.selectCount(new QueryWrapper<SxOrderInfoBrush>().eq("sign_id", sxSignContractBrush.getSignId()));
        sxOrderInfoBrush.setPayStage(String.valueOf(orderNum+1));
        sxOrderInfoBrush.setSignId(sxSignContractBrush.getSignId());
        sxOrderInfoBrush.setYuankeOrderNo(yuankeOrderNo);
        sxOrderInfoBrush.setPaySerialNumber(payData.getString("trade_no"));
        sxOrderInfoBrush.setOrderStatus("1");
        sxOrderInfoBrush.setPayAmount(new BigDecimal(payData.getString("total_amount")));
        sxOrderInfoBrush.setBody(payData.toString());
        sxOrderInfoBrush.setCreateTime(new Date());
        sxOrderInfoBrush.setAliAccountId(sxSignContractBrush.getAliAccountId());
        sxOrderInfoBrush.setHeyeEquityCardId(receiveId);
        if(StringUtils.isNotBlank(sxSignContractBrush.getPayAccount())){
            sxOrderInfoBrush.setPayAccount(sxSignContractBrush.getPayAccount());
        }else {
            sxOrderInfoBrush.setPayAccount(payData.getString("buyer_id"));
        }

        // 检查是否有效
        boolean isValid = checkIfValid(sxOrderInfoBrush.getPayAccount(),sxOrderInfoBrush.getAliAccountId());
        sxOrderInfoBrush.setValidStatus(isValid ? "1": "0"); // 1 表示有效，0 表示无效
        sxOrderInfoBrush.setChannelCode(sxSignContractBrush.getChannelCode());
        sxOrderInfoBrushMapper.insert(sxOrderInfoBrush);
        log.info("创建(刷单)订单结束");

        return sxOrderInfoBrush;
    }

    @Override
    public SxOrderInfoBrush createOrderBrushByPay(SxSignContractBrush sxSignContractBrush,String yuankeOrderNo,String receiveId,JSONObject payData) {
        log.info("进入创建(刷单)单签约订单");
        SxOrderInfoBrush sxOrderInfoBrush = new SxOrderInfoBrush();
        sxOrderInfoBrush.setOrderId(String.valueOf(SnowflakeIdUtils.generateId()));
        sxOrderInfoBrush.setPhoneNo(sxSignContractBrush.getPhoneNo());
        Long orderNum = sxOrderInfoBrushMapper.selectCount(new QueryWrapper<SxOrderInfoBrush>().eq("sign_id", sxSignContractBrush.getSignId()));
        sxOrderInfoBrush.setPayStage(String.valueOf(orderNum+1));
        sxOrderInfoBrush.setSignId(sxSignContractBrush.getSignId());
        sxOrderInfoBrush.setYuankeOrderNo(yuankeOrderNo);
        sxOrderInfoBrush.setPaySerialNumber(payData.getString("trade_no"));
        sxOrderInfoBrush.setOrderStatus("1");
        sxOrderInfoBrush.setPayAmount(new BigDecimal(payData.getString("total_amount")));
        sxOrderInfoBrush.setBody(payData.toString());
        sxOrderInfoBrush.setCreateTime(new Date());
        sxOrderInfoBrush.setAliAccountId(sxSignContractBrush.getAliAccountId());
        sxOrderInfoBrush.setHeyeEquityCardId(receiveId);
        if(StringUtils.isNotBlank(sxSignContractBrush.getPayAccount())){
            sxOrderInfoBrush.setPayAccount(sxSignContractBrush.getPayAccount());
        }else {
            sxOrderInfoBrush.setPayAccount(payData.getString("buyer_login_id"));
        }

        // 检查是否有效
        boolean isValid = checkIfValid(sxOrderInfoBrush.getPayAccount(),sxOrderInfoBrush.getAliAccountId());
        sxOrderInfoBrush.setValidStatus(isValid ? "1": "0"); // 1 表示有效，0 表示无效
        sxOrderInfoBrush.setChannelCode(sxSignContractBrush.getChannelCode());
        sxOrderInfoBrushMapper.insert(sxOrderInfoBrush);
        log.info("创建(刷单)单签约订单结束");

        return sxOrderInfoBrush;
    }

    /**
     * 判断支付账号和支付宝账户在过去7天内是否有有效订单
     *
     * @param payAccount    支付账号
     * @param aliAccountId  支付宝账户ID
     * @return 是否有效
     */
    private boolean checkIfValid(String payAccount, String aliAccountId) {
        Date sevenDaysAgo = DateUtils.addDays(new Date(), -7);

        // 查询支付账号和支付宝账户在过去7天内的有效订单数量
        int count = Math.toIntExact(sxOrderInfoBrushMapper.selectCount(new QueryWrapper<SxOrderInfoBrush>()
                .eq("pay_account", payAccount)
                .eq("ali_account_id", aliAccountId)  // 新增对支付宝账户的判断
                .eq("valid_status", "1")
                .ge("create_time", sevenDaysAgo)));

        // 如果过去7天内没有有效订单，则返回true
        return count == 0;
    }

    @Override
    public ResponseResult getSignUrlById(String signId) {
        SxSignContractBrush sxSignContractBrush = sxSignContractBrushMapper.selectOne(new QueryWrapper<SxSignContractBrush>().eq("sign_id", signId));
        return ResponseResult.success(sxSignContractBrush.getSignUrl());
    }

    @Override
    public ResponseResult unSign(String phoneNo){
        try {
            SxSignContractBrush sxSignContractBrush = sxSignContractBrushMapper.selectOne(new QueryWrapper<SxSignContractBrush>().eq("phone_no", phoneNo).eq("is_sign_type", "1"));
            if(ObjectUtil.isEmpty(sxSignContractBrush)){
                return ResponseResult.error("该手机号不存在已签约的刷单签约单");
            }
            String signId = sxSignContractBrush.getSignId();

            //调用支付宝解约接口
            SxAliAccountInfo sxAliAccountInfo = sxAliAccountInfoMapper.selectById(sxSignContractBrush.getAliAccountId());
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig(sxAliAccountInfo));

            // 构造请求参数以调用接口
            AlipayUserAgreementUnsignRequest request = new AlipayUserAgreementUnsignRequest();
            AlipayUserAgreementUnsignModel model = new AlipayUserAgreementUnsignModel();

            // 设置支付宝系统中用以唯一标识用户签约记录的编号（用户签约成功后的协议号 ）
            model.setAgreementNo(sxSignContractBrush.getSignSerialNumber());

            // 设置用户的支付宝账号对应的支付宝唯一用户号
            model.setAlipayUserId(sxSignContractBrush.getAlipayUserId());

            // 设置协议产品码
            model.setPersonalProductCode(sxAliAccountInfo.getPersonalProductCode());

            // 设置代扣协议中标示用户的唯一签约号(确保在商户系统中
            model.setExternalAgreementNo(sxSignContractBrush.getSignId());

            // 设置签约协议场景
            model.setSignScene("INDUSTRY|DEFAULT_SCENE");
            request.putOtherTextParam("app_auth_token", sxAliAccountInfo.getAppAuthToken());  //从支付宝账户获取
            request.setBizModel(model);
            AlipayUserAgreementUnsignResponse response = alipayClient.execute(request);
            log.info(phoneNo+"请求解约"+sxSignContractBrush.getAlipayUserId());
            //支付宝返回消息体
            System.out.println(response.getBody());

            if (response.isSuccess()) {
//            System.out.println("调用成功");
                log.info("调用成功");
                //更新签约表状态
                LambdaUpdateWrapper<SxSignContractBrush> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.set(SxSignContractBrush::getUpdateTime,new Date());
                updateWrapper.set(SxSignContractBrush::getIsSignType,"0");
                updateWrapper.eq(SxSignContractBrush::getSignId,signId);
                baseMapper.update(new SxSignContractBrush(),updateWrapper);

            } else {
//            System.out.println("调用失败");
                log.error("调用失败");
                return ResponseResult.error("解约失败");
            }
        }catch (Exception e){
            log.error("调用成功");
            return ResponseResult.error("解约失败");
        }
        return ResponseResult.success("解约成功");
    }

    @Override
    public ResponseResult signAndPayHy(SxSignContractBrushDto sxSignContractBrushDto, HttpServletRequest request) throws ServiceException {
        log.info("生成荷叶签约并支付链接(刷单)开始");

        // 获取配置的刷单限制天数
        SxConfigInfo sxConfigInfo = sxConfigInfoMapper.selectOne(null);
        Integer brushLimitDays = sxConfigInfo.getBrushLimitDays();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算限制天数前的日期
        LocalDate limitDate = currentDate.minusDays(brushLimitDays);

        // 检查在限制天数内是否存在订单记录
        boolean phoneNoExists = sxOrderInfoBrushMapper.exists(
                new QueryWrapper<SxOrderInfoBrush>()
                        .eq("phone_no", sxSignContractBrushDto.getPhoneNo())
                        .ge("create_time", limitDate)
        );

        if (phoneNoExists) {
            return ResponseResult.error("该手机号在限制天数内已下单，请勿重复下单");
        }

        SxAliAccountInfo sxAliAccountInfo = null;

        //从配置表获取支付宝账号
        if (StringUtils.isNotBlank(sxSignContractBrushDto.getAliAccountId())) {
            sxAliAccountInfo = sxAliAccountInfoMapper.selectOne(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContractBrushDto.getAliAccountId()));
        } else {
            List<SxAliAccountInfo> sxAliAccountInfoList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("account_type", "2"));
            if (sxAliAccountInfoList.isEmpty()) {
                throw new ServiceException("没有可用的支付宝账户，请联系管理员！");
            }
            //打乱支付宝账户列表取出第一个
            Collections.shuffle(sxAliAccountInfoList);
            sxAliAccountInfo = sxAliAccountInfoList.get(0);
        }

        if (sxAliAccountInfo == null) {
            throw new ServiceException("没有可用的支付宝账户，请联系管理员！");
        }

        String signId = String.valueOf(SnowflakeIdUtils.generateId());

        //获取当前时间
        Date nowDate = new Date();

        //保存签约信息
        SxSignContractBrush sxSignContractBrush = new SxSignContractBrush();
        sxSignContractBrush.setSignId(signId);
        sxSignContractBrush.setPhoneNo(sxSignContractBrushDto.getPhoneNo());
        sxSignContractBrush.setChannelCode(sxSignContractBrushDto.getChannelCode());
        sxSignContractBrush.setPayType("0");
        sxSignContractBrush.setDeductType(sxAliAccountInfo.getDeductCycleType());//从支付宝账户获取扣款类型
        sxSignContractBrush.setDeductCycle(sxAliAccountInfo.getBrushCycle());//从支付宝账户获取周期
        sxSignContractBrush.setIsSignType("2");
        sxSignContractBrush.setAliAccountId(sxAliAccountInfo.getAliAccountId());//从支付宝账户获取id
        sxSignContractBrush.setCreateTime(nowDate);

        //生成链接
        String signUrl = signAndAlipay(sxSignContractBrush, sxAliAccountInfo,signAndPayBrushCallBackHyUrl);


        sxSignContractBrush.setSignUrl(signUrl);
        sxSignContractBrushMapper.insert(sxSignContractBrush);

        //获取支付宝跳转链接
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("url", signUrl);
        mapResult.put("signId", signId);

        return ResponseResult.success(mapResult);
    }

    public AlipayConfig getAlipayConfig(SxAliAccountInfo sxAliAccountInfo) {
        String privateKey = sxAliAccountInfo.getPrivateKey();
        String alipayPublicKey = sxAliAccountInfo.getAlipayPublicKey();
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        //alipayConfig.setAppId("2021004137633645");
        alipayConfig.setAppId(sxAliAccountInfo.getAppId());
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

}

